
var realname_type = {
  ED:'二代身份证',
  YD:'一代身份证',
  JR:'军人证',
  JS:'机动车驾驶证',
  HK:'户口薄',
  HZ:'护照',
  HX:'回乡证',
  TB:'台胞',
  GA:'港澳通行证',
  HY:'海员证',
  YJ:'外国人永久居住证',
  CR:'外国人出入境证'
}	

var serviceFee,
  unitPrice = 0,
  carrigeFee = 0,
  ord_on_duty = 8,
  ord_off_duty = 18,
  train_info = [],
  confirmed = false;

function data2table(json){
	
	$('#tip').hide();
	
	setTimeout(function(){ $('#loading,#loading-content').hide(); },1200);
	
	
	//处理座次
	var $seat_type = $('#tik_seat_type');
	
	train_info = json.data[0];
	//显示错误
	if( json.status != 0 && json.status != -122 ){
		$('#tip').show().html( '<span class="err" style="display:inline;">'+json.msg+'</span>');
		return false;
	}
			
	
		
	if(train_info.presell=='1') { 
		presell = false; 
		$('#tip').show()
		.text('尊敬的用户，该车次票不在预售期！请选其他时间！')

		$('#departureDate').focus();
		$seat_type.empty().append('<option value="0">请选择</option>');
		return false;
	}
	else if(train_info.presell=='2'){
		presell = false; 
		$('#tip').show()
		.text('尊敬的用户，该车次车票在开车前无法送达！请选其他时间！')

		$('#departureDate').focus();
		$seat_type.empty().append('<option value="0">请选择</option>');
		return false;
	}
	
	if($('#tik_departure_station').val()=='香港'||$('#tik_arrival_station').val()=='香港'||$('#tik_departure_station').val()=='九龙'||$('#tik_arrival_station').val()=='九龙'){
		$('#tip').show()
		.text('该地区暂不提供服务！')
		return false;
	}

	
	//显示车票信息
	var back_url = 'search.php?from='
		+train_info.tn_sta_depart.replace(/(东|西|南|北|虹桥)$/g,'').replace(/武昌|汉口/g,'武汉')
		+'&to='+train_info.tn_sta_arrive.replace(/(东|西|南|北|虹桥)$/g,'').replace(/武昌|汉口/g,'武汉')
		+'&departureDate='+$('#departureDate').val()+'&trainNumber='+train_info.train_name;
		
	$('#ticket_info').html('<span style="font-weight:bold">'+train_info.train_name+' [<a href="'+back_url+'">修改</a>] '
		+train_info.tn_sta_depart+train_info.sta_time_depart+' -> '+train_info.tn_sta_arrive+train_info.sta_time_arrive+'</span>');
		
	
	
	var seat_type_val = $('#seatType').val()=='' ?  $seat_type.val() : $('#seatType').val();//记录当前值
	
	$seat_type.empty().append('<option value="0">请选择</option>');

	var available = false;
	var price = train_info.tik_price_info;
	for(var i in price){
		var seat = price[i];
		for(var n in seat){
			if(seat[n].available == 'true'){
				
				$op = $('<option></option>')
					.attr('price',seat[n].unitPrice)
					.val(seat[n].typeCode)
					.text(seat[n].name+seat[n].unitPrice+' 元');
				
				if(seat_type_val==seat[n].typeCode)
					//alert(seat_type_val+':'+seat[n].typeCode);
					$op.attr('selected','selected');
				
				$seat_type.append($op);
				//'<option price="'+seat[n].unitPrice+'" value="'+seat[n].typeCode+'" >'
					//+seat[n].name+seat[n].unitPrice+' 元</option>');
				available = true;
				if(seat[n].typeCode == seat_type_val)
					unitPrice = seat[n].unitPrice;
			}
		}
	}
	//alert(seat_type_val);
	//$seat_type.val( seat_type_val );//恢复当前选择值
	
	show_accept();

	set_total_money();
	
	if(!available) { 
		$('#tip').show()
		.text('尊敬的用户，该车次票已售完！请选其他时间！')
		
		$('#departureDate').focus();
		
	}
	
}

function show_accept(){
		
	if( $('#tik_seat_type').val() == '0' ) return false;
	
	$('#accept').empty();
	
	var the_price = $('#tik_seat_type :selected').attr('price');
		the_price = Number(the_price);
	var accept_length = 0;	
	
	$.each(train_info.tik_price_info,function(i,n){

		$.each(n,function(k,v){
		
			if(the_price<v.unitPrice||$('#tik_seat_type').val()==v.typeCode||v.available==false) return ;
			
			$('#accept').append(' <input type="checkbox" value="'
			+ v.typeCode + '*' + v.name + '*' + v.unitPrice
			+'" /> <label>'+ v.name +'</label> ');
			
			accept_length++;
		
		});
		
	});
	
	if( accept_length == 0 ) {
		
		$('#accept_hint').hide();
	
		$('#accept').hide();
		
		return false;
	}
	
	$('#accept_hint').show();
	
	$('#accept').show();
		
}

function get_accept(){
	
	var accept = [];
	
	$('#accept :checked').each(function( i , n ){
		
		accept.push( n.value );
		
	});
	
	return accept.join('|');
	
}
	
function set_total_money(){
		
	var total_money = unitPrice*amount + carrigeFee + serviceFee*amount; 
	//var payserviceFeeReal = total_money*payserviceFee;

	//total_money += payserviceFeeReal; 
	
	$('#payFee').text(unitPrice*amount);
	$('#carriageFee').text(carrigeFee);
	$('#serviceFee').text(serviceFee*amount);
	//$('#extraFee').text(payserviceFeeReal.toFixed(2));
	$('#pay_total_amount').text(total_money);
	
}


function create_realname_fields( amount ){
	
	var item = '',tmp = '';


	for(var i=0;i<amount;i++){
	  
	    for(var n in realname_type){
		  tmp +=  '<option value="'+n+'">'+realname_type[n]+'</option>';
		}
	  
	      item += '<div class="realname-filed">' + '证件类型:<select class="cert_type">' + tmp 
		+ '</select>姓名:<input class="cert_name required" type="text" size="10" value=""><span class="err">必须填写</span> '
		+'证件号码:<input class="cert_no required" type="text" size="22"value=""><span class="err">没有正确填写</span></div>';
		
	}
	$('#shiming').show();
	$('#shiming_hint').show();
	$('#shiming-fields').html(item);
}

function get_realname_fields(){
	
	var item = [];
	
	$('#shiming-fields').children()
	.each(function(){
		var arr = [];
		$(':input',$(this)).each(function(){
			arr.push( $(this).val() );
		});
		arr.splice(1,0,$('#tik_seat_type').val());
		arr = arr.join('*');
		item.push( arr );
	});
	
	return item.join('|');
}



function is_onduty(ord_on_duty,ord_off_duty){
	//是否在工作时间
	var d = new Date();
	var h = d.getHours();
	var m = d.getMinutes();
	if( ord_on_duty > h || h >= ord_off_duty ){
		return false;
	}
	return true;
}


function fill_address( address ){
	
	create_select_item(cities,$prov);//

	if(address){
		$prov.val( address.frt_recev_addr_prov );
	}

	//create_select_item(cities[$prov.val()],$city);
	
	$.each(cities[$prov.val()],function(k,v){
		var $op = $('<option value=""></option>').text(k).val(k);
		if(k==address.frt_recev_addr_cityname)
			$op.attr('selected',true);
		$city.append($op);
	});


	$('#frt_recev_addr_cityid').val(cities[$prov.val()][$city.val()]['cid']);

	$.each(cities[$prov.val()][$city.val()]['dist'],function(k,v){
	
		var $op = $('<option value=""></option>').text(k).val(k);
		if(k==address.frt_recev_addr_distname)
			$op.attr('selected',true);
		
		$dist.append($op);
	
	});
	
	$('#frt_recev_addr_distid').val(cities[$prov.val()][$city.val()]['dist'][$dist.val()]);

	
	carrigeFee = cities[$prov.val()][$city.val()]['cf']/100;
		
	$('#frt_recev_addr_cityid').val(cities[$prov.val()][$city.val()]['cid']);
	
	$('#fee_carriage_id').val(cities[$prov.val()][$city.val()]['cfid']);
	
	set_total_money();
	
	if(address)
	$('#address-fields :text').each(function(n,v){
		$(v).val( address[$(v).attr('name')] );
	});
}

function create_select_item( data, $select ){
	//var val = $select.val();
	
	$select.html('<option value="0">请选择</option>');
	$.each(data, function(k,v){
		var $op = $('<option></option>').val(k).text(k);
		$select.append($op);
	});
	//if(val!=0)$select.val(val);
}


function show_address(){
	
	var address = user_info['address'];
	
	if(address==null) orderlogin(get_user_info);
	
	

	if(!address) return false;
	
	var $address = $('#address');
	
	$address.empty().show();
	
	if($.isEmptyObject(address))
		$address.append('<li>您还没有保存过地址！（系统会自动保存您填写过的地址。）</li>');

	$.each(address,function(t,v){
		$address.append('<li><input type="radio" name="addressinput" value="'+t+'" /> '+v.frt_recev_addr_detail+'</li>');
	});
	$('input',$address).click(function(){
		
		fill_address(address[$(this).val()]);
	});
	
	return false;
}

function get_user_info(){

	
	
		var url = '/account/userstatus.php?action=get_user_info';
		
		$.get(encodeURI(url),function(json){
		
			user_info = json;
			
			show_address();
			
			show_realname();
			
			update_login_status();
			
			close_popup();
		
		},'json');
		
	
	
	

}

function show_realname(){

	realname = user_info.realname;
	
	if(realname==null) orderlogin(get_user_info);
	
	
	if( !realname ) return false;
	
	var $shiming_list = $('#shiming-list');
	
	$shiming_list.empty().show();
	
	if($.isEmptyObject(realname))
		$shiming_list.append('<span> 您还没有保存过实名！（系统会自动保存您填写过的实名信息。）</span>');
		
	$.each(realname,function(k,v){
		$shiming_list.append('<span> <input type="Checkbox" name="realname" value="'
			+(k)+'" />  '+v.cert_name+'</span>');
	});
	
	$('input',$shiming_list).click(function(){
	
		
		var $fields = $('#shiming-fields').children();
		
		
		
		var $checks = $('#shiming-list :checked');
		
		$checks.each(function(i,n){
			
			//if(i>realname.length)return false;
			
			var field = $fields.eq(i);

			$('.cert_name',field).val(realname[n.value]['cert_name']);
			$('.cert_type',field).val(realname[n.value]['cert_type']);
			$('.cert_no',field).val(realname[n.value]['cert_no']);
			
		});

		if(!this.checked)$fields.eq(this.value).find('input').val('');
		
	});
}



//--------------------------------------------------------华丽的分割线----------------------------------------------------------------//


jQuery(function($){
	
	serviceFee = Number( $('#fee_service_base').val() )/100;
	//payserviceFee = 0;Number($('#fee_payservice_rate').val());
	amount = Number($('#tik_amount').val());
	
	isRealName = /^[dDgGcC]/.test( $('#tik_train_name').val() );

	$prov = $('#frt_recev_addr_prov');
	$city = $('#frt_recev_addr_cityname');
	$dist = $('#frt_recev_addr_distname');
	
	//输入日期	
	$('#departureDate').datepicker({dateFormat:'yy-mm-dd',minDate:'0',maxDate:'+29D',numberOfMonths: 2});
	
	//Ajax请求车票信息
	$.get ( encodeURI('/api/search.php'+location.search),data2table,'json' );
	
	//营业时间提示
	if(!is_onduty(ord_on_duty,ord_off_duty)) 
		$('#tip').show()
		.text('当前订单送票城市的营业时间为'+ord_on_duty+':00'+'-'+ord_off_duty+':00,您的订单支付后要等到营业时间才能处理!');

	
	$('#loading,#loading-content').show();
		
	create_select_item(cities,$prov);
	
	//fill_address(  );

	$('#frt_recev_addr_prov').change(function(){
		create_select_item(cities[$prov.val()],$city);
	});
	
	$('#frt_recev_addr_cityname').change(function(){
		
		if($(this).val()==0) return false;
		
		create_select_item(cities[$prov.val()][$city.val()]['dist'],$dist);
		
		carrigeFee = cities[$prov.val()][$(this).val()]['cf']/100;
		
		$('#frt_recev_addr_cityid').val(cities[$prov.val()][$(this).val()]['cid']);
		
		$('#fee_carriage_id').val(cities[$prov.val()][$(this).val()]['cfid']);
		
		set_total_money();

	});
	
	
	//添加地区名
	$('#frt_recev_addr_distname').change(function(){
		$('#frt_recev_addr_distid').val(cities[$prov.val()][$city.val()]['dist'][$(this).val()]);
	});
	
	
	$('#show_address').click(show_address);
	
	//show_address();
	
	
	if( isRealName ) create_realname_fields( amount );	
	
	
	$('#departureDate').change(function(){
		$('#loading,#loading-content').show();
		$('#tik_train_dt').val($(this).val());
		$.get(encodeURI('/api/search.php?from='+$('#tik_departure_station').val()+'&to='+$('#tik_arrival_station').val()
				+'&trainNumber='+$('#tik_train_name').val()+'&departureDate='+$('#departureDate').val()),
			function(json){ 
				data2table( json ); 
		},'json');
	
	});
	
	//显示第二选择
	$('#tik_seat_type').change(function(){ 	
		show_accept(); 
		unitPrice = Number($(':selected',this).attr('price')); 
		set_total_money();
	});
	
	//显示实名制
	$('#tik_amount').change(function(){
		
		amount = Number($(this).val());
		
		set_total_money();
		
		if( isRealName ) create_realname_fields( amount );

	});
	
	
	
	
	$('#open-textarea').click(function(){ $('#frt_recev_want_memo').show();$(this).hide(); });//显示备注填写框
	
	//输入检查
	$('#agree').change(function(){
		if(!$(this).is(':checked'))
			$('#order2-submit').attr('disabled','disabled').addClass('disabled');
		else 
			$('#order2-submit').removeAttr('disabled').removeClass('disabled');
	});
	

	$('#order-form').submit(function(){
		
		if(!$('#agree').is(':checked')) return false;
		
		
		
		allow_submit = true;
		
		var cert_no = [];
		
		$('.cert_no').each(function(){

			var cert_type = $(this).parent().find('.cert_type').val();
			if(cert_type!='ED'&&cert_type!='YD') return;
			var checked = CheckIdCard($(this).val());
			
			if($(this).val() in cert_no){
				alert('身份证号码不能重复，请重新填写！');
				$(this).focus();
				allow_submit = false;
				return false;
			}
			
			cert_no[$(this).val()]=$(this).val();
			
			if(!checked){
				allow_submit = false;
				$(this).focus();
				return false;
			}
		});
		
		//allow_submit = false;
		
		if($prov.val()=="甘肃"){
			
			var date = new Date($('#departureDate').val().replace(/-/g,'/')).getTime();
			var now = new Date().getTime();
			
			if(date-3*24*60*60*1000<now) 
			{
				allow_submit = false;
			
				alert('您所在城市现在只能订购4天以后的车票！');
			
				return false;
			}
		}
		
		if($prov.val()=="重庆"||$prov.val()=="四川"){
			
			var date = new Date($('#departureDate').val().replace(/-/g,'/')).getTime();
			var now = new Date().getTime();
			
			if(date-3*24*60*60*1000<now) 
			{
				allow_submit = false;
			
				alert('您所在城市现在只能订购3天以后的车票！');
			
				return false;
			}
		}
		 
		$('#order2-submit').attr('disabled','disabled').addClass('disabled');//防止重复提交
		
		if(!confirmed){
			if(!is_onduty(ord_on_duty,ord_off_duty)){ 
			
				var txt = '当前订单送票城市的营业时间为'+ord_on_duty+':00'+'-'
					+ord_off_duty+':00,您的订单支付后要等到营业时间才能处理,您要继续支付么?';
					
				if (!confirm(txt))
				{
					allow_submit = false;
				}
			}
		}
		
		//下拉列表处理
		$('select',this).each(function(){
		
			if($(this).is('#frt_recev_addr_prov') || $(this).is('#frt_recev_addr_cityname')) return ;
			
			if($(this).val()=='0'){
				$(this).next('.err').remove();
				$(this).after('<span class="err" style="display:inline">请选择</span>');
				allow_submit = false;
				$(this).change(function(){
					$(this).next('.err').remove();
				});
			}
		});
		
		//必填字段处理
		$('.required',this).each(function(){
			if($(this).val()==''){
				$(this).addClass('ui-state-error');
				$(this).next().show();
				allow_submit = false;
			}
		})
		.focus(function(){ 
			$(this).removeClass('ui-state-error').next().hide(); 
		});
		
		//特殊字段验证
		var zipCode = /^\d{6}$/;
		var phone = /^\d{11}$/;
		var mail  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
		if(!zipCode.test($('#frt_recev_addr_zipcode').val())){
			$('#frt_recev_addr_zipcode').next().show();
			allow_submit = false;
		}
		 if(!phone.test($('#frt_recev_mobile').val())){
			$('#frt_recev_mobile').next().show();
			allow_submit = false;
		} 
		 
		 
		 if($('#frt_recev_mail').val()!=undefined){
			 if(!mail.test($('#frt_recev_mail').val())){
				 $('#frt_recev_mail').next().show();
				 allow_submit = false;
			 } 
			 
		 }
		
		$('#shiming-fields')
		.children()
		.each(function(){
			var cert_type = $('.cert_type',$(this)).val();
			if(cert_type=='ED'||cert_type=='YD'){
				var cert_no = $('.cert_no',$(this)).val();
				if(cert_no.length==15||cert_no.length==18) {
				}
				else{
					
					allow_submit=false;
					$('.cert_no',$(this)).addClass('ui-state-error')
					.next().text('身份证为15位或18位！').show();
				}
			}
		});

		if( !allow_submit ) {
			$('#order2-submit')
				.removeAttr('disabled').removeClass('disabled');
			return false;
		}
		
		
		
		//转换数据格式
		if( isRealName )
			$('#tik_cert_info').val( get_realname_fields() );
			
		$('#tik_seat_option').val( get_accept() );
		
		var form = $('#order-form').serializeArray();
		
		//验证订单
		$.post(encodeURI('/api/order_ajax.php'),
			
			form,
			
			function(xml){
			 
				if( Number($('error_code',xml).text())<=0 )
				{
					if  (Number($('error_code',xml).text()) == -1) //or_need_login 
					{
							callback = function(){
								$('#order-form').submit();
							}
							orderlogin(callback);
							allow_submit = false;
					}
					else
					{
						alert ($('error_msg',xml).text());
						allow_submit = false; 
					}
					
					$('#order2-submit').removeAttr('disabled').removeClass('disabled');
					
				}
				else{
					if($('new_reg_user',xml).text()=='1')alert('订单创建成功，您填写的手机号后4位就是您的订单查询密码。');
					location.href = "pay.php?oid="+$('error_code',xml).text()+"&newreg="+$('new_reg_user',xml).text();
				}
				
				
			}
		);
		
		return false;
	});

	

});
